//
//  SMSRequestProvider.m
//  SulitLoan
//
//  Created by 虞嘉伟 on 2025/2/26.
//  
  

#import "AddressRequestProvider.h"
#import "AddressRequest.h"
//#import "NSArray+JSONReadWrite.h"


@implementation AddressRequestProvider
+ (void)requestAddressWithSuccess:(void(^)(NSArray *arr))success failure:(void(^)(YTKRequest *request))failure {
    
    if ([NSFileManager.defaultManager fileExistsAtPath:[self localCachePath]]) {
        NSArray *address = [NSArray performSelector:@selector(JSONWithContentsOfFile:) withObject:[self localCachePath]];
        if (address.count) {
            success(address);
            return;
        }
    }
    AddressRequest *request = [AddressRequest new];
    [request startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSDictionary *dict = request.responseObject;
        if (![dict isKindOfClass:NSDictionary.class]) {
            !failure ?: failure(request);
            return;
        }
        if ([dict[@"weeps"] intValue] == 0) {
            // 成功
            NSArray *address = dict[@"bounding"][@"sensitive"];
            [address performSelector:@selector(writeToJSONFile:atomically:) withObject:[self localCachePath] withObject:@(YES)];
            //[address writeToJSONFile:[self localCachePath] atomically:YES];
            !success ?: success(address);
        } else {
            !failure ?: failure(request);
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        !failure ?: failure(request);
    }];
}


+ (NSString *)localCachePath {
    NSString *cachesDirectory = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    NSFileManager *fm = NSFileManager.defaultManager;
    NSString *filePath = [cachesDirectory stringByAppendingPathComponent:@"api"];
    if (![fm fileExistsAtPath:filePath]) {
        // 创建目录
        NSError *error = nil;
        BOOL success = [fm createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:&error];
        NSLog(@"---localCachePath: 目录创建%@: %@", success ? @"成功" : @"失败", success ? filePath : @"");
    } else {
        
    }
    return [filePath stringByAppendingPathComponent:@"address.json"];
}



@end
